package com.pg.agent.engine.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.pg.agent.engine.client.dto.AgentExeDTO;
import com.pg.agent.engine.client.model.PromptConstant;
import com.pg.agent.engine.client.model.SessionObject;
import com.pg.agent.engine.client.model.agent.AIAgent;
import com.pg.agent.engine.client.model.environment.AIEnvironment;
import com.pg.agent.engine.client.model.environment.Config;
import com.pg.agent.engine.client.model.llm.ComponentLLM;
import com.pg.agent.engine.client.model.sop.AISOP;
import com.pg.agent.engine.client.model.sop.ShareMemory;
import com.pg.agent.engine.client.model.state.AIState;
import com.pg.agent.engine.service.service.SopInitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Dell
 */
@Slf4j
@Service("sopInitService")
public class SopInitServiceImpl implements SopInitService {


    @Value("${spring.profiles.active}")
    private String profile;
    private static final int expiredTime = 60 * 60 * 60;


    @Override
    public SessionObject init(AgentExeDTO AgentExeDTO) {
        SessionObject SessionObject = new SessionObject();
        AISOP aisop = getAiSOP(1L);
        AIEnvironment aiEnvironment = initEvnironment(aisop);

        SessionObject.setAiEnvironment(aiEnvironment);
        SessionObject.setAiSOP(aisop);
        return SessionObject;
    }

    public AIEnvironment initEvnironment(AISOP aisop) {
        AIEnvironment aiEnvironment = new AIEnvironment();
        ShareMemory shareMemory = new ShareMemory();
        shareMemory.setLongMemory(new ArrayList<>());
        shareMemory.setShortMemory("");

        aiEnvironment.setShareMemory(shareMemory);
        Map<String, AIAgent> evnAgentMap = new HashMap<>();
        Map<String, String> summarySystemPrompt = new HashMap<>();
        Map<String, String> summaryLastPrompt = new HashMap<>();
        Map<String, String> environmentPrompt = new HashMap<>();
        for (Map.Entry<String, AIState> aiState : aisop.getStates().entrySet()) {
            AIState value = aiState.getValue();
            summarySystemPrompt.put(value.getName(), PromptConstant.DEFAULT_ENVIRONMENT_SUMMARY_SYSTEM_PROMPT);
            summaryLastPrompt.put(value.getName(), PromptConstant.DEFAULT_ENVIRONMENT_SUMMARY_LAST_PROMPT);
            environmentPrompt.put(value.getName(), value.getEnvironmentPrompt());
            for (AIAgent aiAgent : value.getAiAgentList()) {
                evnAgentMap.put(aiAgent.getName(), aiAgent);
            }
        }
        //environment.setAgents(evnAgentMap);
        aiEnvironment.setEnvironmentPrompt(environmentPrompt);
        aiEnvironment.setSummarySystemPrompt(summarySystemPrompt);
        //aiEnvironment.setSummaryLastPrompt(summaryLastPrompt);
        Config config = new Config();
        config.setApiKey("c6fd6677ad6549b1ba87cefb02785101");
        config.setApiBase("https://test-openai-419.openai.azure.com/");
        config.setOpenaiApiType("");
        config.setTopK("3");
        config.setProxy("");
        config.setMaxChatHistory(10);
        aiEnvironment.setConfig(config);
        return aiEnvironment;
    }


    private AISOP getAiSOP(Long versionId){
        AISOP aisop = null;
        aisop =  initAiSop();
        aisop.setDescription("");
        return aisop;
    }


    public AISOP initAiSop() {
        // 初始化SOP
        AISOP aisop = new AISOP();
        aisop.setId(1L);
        aisop.setName("问答SOP");
        aisop.setRunMode(0);
        aisop.setSummaryHistory(true);
        aisop.setBeginQuery("你好，请问有什么问题咨询");
//        List<AgentInParamSetDTO> inParamList = startNode.getInParamList();
//        if (CollectionUtil.isNotEmpty(inParamList)) {
//            //判断是否必填
//            for (AgentInParamSetDTO AgentInParamSetDTO : inParamList) {
//                ClifeAssert.bizError(ObjectUtil.isEmpty(AgentInParamSetDTO.getParamCode()), ErrorCodeEnum.LACK_PARAM_CODE);
//                ClifeAssert.bizError(ObjectUtil.isEmpty(AgentInParamSetDTO.getParamName()), ErrorCodeEnum.LACK_PARAM_NAME);
//                ClifeAssert.bizError(ObjectUtil.isEmpty(AgentInParamSetDTO.getRequired()), ErrorCodeEnum.LACK_PARAM_REQUIRE);
//                ClifeAssert.bizError(ObjectUtil.isEmpty(AgentInParamSetDTO.getParamType()), ErrorCodeEnum.LACK_PARAM_TYPE);
//            }
//        }
        // 增加快捷输入标签。
//        if (ObjectUtil.isNotEmpty(startNode.getDesc()) && startNode.getDesc().indexOf("#") > 0) {
//            String[] split = startNode.getDesc().split("#");
//            aisop.setLabelList(Arrays.asList(split));
//        }

        //sop默认大模型
/*        if (startNode.getComponentId() != null) {
            aisop.setComLLM(getLLMComponent(startNode.getComponentId()));
        } else {*/
            //默认ChatGPT-3.5 todo,暂时写死
            aisop.setComLLM(getLLMComponent(138L));
       // }
        //sop关联状态
        Map<String, AIState> aiStateMap = new HashMap<>();
        List<AIState> aIStateList = new ArrayList<>();

        AIState aiState = initStateNodeData(aisop);

        aIStateList.add(aiState);
        aiStateMap = aIStateList.stream().collect(Collectors.toMap(AIState::getName, Function.identity(),(a,b)->a));
        aisop.setStateList(aIStateList);
        aisop.setStates(aiStateMap);

        return aisop;
    }

    /**
     * 同一个意图识别下，不能存在相同名字的场景或agent
     * @param allState
     * @return
     */
    private Boolean judgeSameName(Map<String, String> allState){
        Boolean flag = false;
        if (CollectionUtil.isNotEmpty(allState)){
            Collection<String> name = allState.values();
            Set<String> stringSet = new HashSet<>(name);
            if (name.size()>stringSet.size()){
                flag = true;
            }
        }
        return flag;
    }

    private AIState initStateNodeData(AISOP aisop) {
        AIState aiState = new AIState();
        aiState.setName("问答");
        aiState.setEnvironmentPrompt("");

        Integer maxNum = 10;

        List<AIAgent> aiAgentList = new ArrayList<>();
        List<String> roleList = new ArrayList<>();
        AIAgent aiAgent = initAgent();
        aiAgentList.add(aiAgent);
        roleList.add(aiAgent.getRole());
        // 如果是对话模式，默认添加用户Agent
        if (aisop.isDialogueMode()) {
            AIAgent aiAgentUser = initUserAgent(null);
            aiAgentList.add(aiAgentUser);
        }
        aiState.setAiAgentList(aiAgentList);
        return aiState;
    }



    private ComponentLLM getLLMComponent(Long compId) {
      /*  if (compId != null) {
            Component component = componentGateway.findById(compId);
            if (null != component) {
                Interface interfaces = interfaceGateway.get(component.getInterfaceId());
                ComponentLLM llm = new ComponentLLM();
                if (interfaces == null) {
                    String interfaceList = component.getInterfaceList();
                    JSONArray jsonArray = JSON.parseArray(interfaceList);
                    interfaces = interfaceGateway.get(jsonArray.getLong(0));
                }
                if (interfaces != null) {
                    llm.setUrl(interfaces.getHostUrl() + interfaces.getUrl());
                    llm.setRequestMethod(interfaces.getRequestMethod());
                    llm.setInParam(interfaces.getInParam());
                    llm.setModel(interfaces.getInterfaceName());
                    llm.setType(component.getType());
                }
                return llm;
            }
        }*/

        ComponentLLM llm = new ComponentLLM();
        llm.setUrl("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-0205?access_token=24.e95da8dab8827f286480010f6e0bcff3.2592000.1716212532.282335-49182738");
        llm.setRequestMethod("POST");
        llm.setInParam("");
        llm.setModel("百度千帆");
        llm.setType(0);
        return llm;
    }


    /**
     * @return
     */
    private AIAgent initAgent() {
        AIAgent aiAgent = new AIAgent();
        aiAgent.setName("助手");
        aiAgent.setExecComList(new ArrayList<>());

        ComponentLLM bigModel = getLLMComponent(0L);
        if (null != bigModel) {
            aiAgent.setComLLM(bigModel);
        }

        //指令
        aiAgent.setPrompt("回答用户问题");
        // 配置组件关联关系
        //aiAgent.setApiComponentList(obtainCommonComponent(agentNode));
        // 配置agent出参
        //解析出参的用到的组件参数

        return aiAgent;
    }





    public AIAgent initUserAgent(String userName) {
        AIAgent aiAgent = new AIAgent();
        aiAgent.setName(Optional.ofNullable(userName).orElse("User"));
        aiAgent.setStyle("");
        aiAgent.setRole("User");
        aiAgent.setUser(true);
        return aiAgent;
    }


    private void getDefaultBigComp() {
        if ("dev".equals(profile) || "local".equals(profile)) {

        } else if ("itest".equals(profile)) {

        }

    }

    private void analyzePrompt(String prompt, List<String> userParam, List<String> systemParam, Map<Long, List<String>> compParam) {
        if (ObjectUtil.isEmpty(prompt)) {
            return;
        }
        int l = 0;
        int r = 0;
        char[] chars = prompt.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '{') {
                l = i;
            } else if (chars[i] == '}') {
                r = i;
                String str = prompt.substring(l + 1, r);
                if (str.startsWith("custom")) {
                    userParam.add(str);
                } else if (str.startsWith("sys")) {
                    systemParam.add(str);
                } else if (str.startsWith("comp")) {
                    String[] strings = str.split("-");
                    Long id = Long.valueOf(strings[1]);
                    String code = strings[2];
                    if (compParam.containsKey(id)) {
//                        List<String> codes = compParam.get(id);
//                        codes.add(code);
//                        compParam.put(id,codes);
                        compParam.get(id).add(code);
                    } else {
                        List<String> codes = new ArrayList<>();
                        codes.add(code);
                        compParam.put(id,  codes);
                    }
                }
            }
        }
    }

}
